package jumpingnotes.restlet.resource;

import static jumpingnotes.restlet.ErrorCode.NO_PERMISSION;
import static jumpingnotes.restlet.ErrorCode.OBJECT_NOT_FOUND;
import static jumpingnotes.restlet.ErrorCode.SERVER_INTERNAL_ERROR;

import java.util.ArrayList;
import java.util.List;

import jumpingnotes.model.entity.Group;
import jumpingnotes.model.entity.GroupTopic;
import jumpingnotes.restlet.JsonMapping;

import org.json.JSONObject;
import org.restlet.Context;
import org.restlet.data.MediaType;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.resource.Representation;
import org.restlet.resource.ResourceException;
import org.restlet.resource.Variant;

public class GroupStickyTopicsResource extends BaseResource
{
	private Group group = null;
	private int startIndex = 0;
	private int count = 10;

	@Override
	public void init(Context context, Request request, Response response)
	{
		super.init(context, request, response);

		getVariants().add(new Variant(MediaType.APPLICATION_JSON));

		try
		{
			sessionId = (String) getRequest().getAttributes().get("sessionId");
			checkPermission();

			if (hasPermission())
			{
				// URL: "/groups/{groupId}/stickytopics?startIndex={startIndex}&amp;count={count}"
				String groupIdStr = (String) getRequest().getAttributes().get("groupId");

				String startIndexStr = (String) getRequest().getAttributes().get("startIndex");
				String countStr = (String) getRequest().getAttributes().get("count");

				startIndex = Integer.valueOf(startIndexStr);
				count = Integer.valueOf(countStr);

				int groupId = Integer.parseInt(groupIdStr);
				group = service.findGroupById(groupId);
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	@Override
	public Representation represent(Variant variant) throws ResourceException
	{
		if (!hasPermission())
		{
			return createErrorRepresentation(NO_PERMISSION);
		}

		if (group == null)
		{
			return createErrorRepresentation(OBJECT_NOT_FOUND);
		}

		try
		{
			// get all object
			List<GroupTopic> groupTopicList = service.findStickyTopicByGroupId(group.getGroupId(), startIndex, count);

			// get object count
			int groupTopicListSize = service.findStickyTopicByGroupId(group.getGroupId(), -1, -1).size();

			// create json object
			List<JSONObject> groupTopicJsonList = new ArrayList<JSONObject>();
			for (GroupTopic groupTopic : groupTopicList)
			{
				JSONObject groupTopicJson = JsonMapping.map(groupTopic);
				groupTopicJsonList.add(groupTopicJson);
			}

			JSONObject groupTopicsJson = new JSONObject();
			groupTopicsJson.put("count", groupTopicListSize);
			groupTopicsJson.put("grouptopics", groupTopicJsonList);

			return createJsonRepresentation(groupTopicsJson);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return createErrorRepresentation(SERVER_INTERNAL_ERROR);
		}
	}
}
